package org.belkodevelop.journal.dao;

import org.belkodevelop.journal.domain.JournalItem;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public class JournalDAOimpl implements JournalDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<JournalItem> getJournalItems(Integer start, Integer end, Long userId) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("from JournalItem j where j.user.id = :user_id order by j.date desc");
        //query.setCacheable(true);
        query.setParameter("user_id", userId);
        if (start != null) {
            query.setFirstResult(start);
        }
        if (end != null) {
            query.setMaxResults(end);
        }
        return (List<JournalItem>)query.list();
    }

    @Override
    public List<JournalItem> getJournalItems(Date start, Date end, Long userId) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("from JournalItem j " +
                        "where j.user.id = :user_id " +
                        "and (j.date >= :start or :start is null) " +
                        "and (j.date <=:end or :end is null) order by j.date");
        //query.setCacheable(true);
        query.setParameter("user_id", userId);
        query.setParameter("start", start);
        query.setParameter("end", end);
        return (List<JournalItem>)query.list();
    }

    @Override
    public void addJournaItem(JournalItem journalItem) {
        sessionFactory.getCurrentSession().save(journalItem);
    }

    @Override
    public JournalItem getJournalItem(long id) {
        return (JournalItem) sessionFactory.getCurrentSession().get(JournalItem.class, id);
    }

    @Override
    public void deleteJournalItem(long id) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("delete from JournalItem j where j.id= :id");
        query.setParameter("id", id);
        query.executeUpdate();
    }

}
